package svrConnectMgr

import (
	"fmt"
	"fronter/config"
	redisgw "fronter/redisGw"
	"net"
	"os"
	"sync"

	"github.com/lesismal/arpc"
	"github.com/sirupsen/logrus"
)

type MyServer struct {
	ArpcSvr *arpc.Server
}

func init() {

}

//单例返回Server
var once sync.Once
var serverIns MyServer

func GetSingleSvr() *MyServer {
	once.Do(func() {
		serverIns = MyServer{
			ArpcSvr: arpc.NewServer(),
		}
		logrus.Info("arpc server created!")
	})

	return &serverIns
}

func (p *MyServer) Run(addr string, port uint32) {
	portRange := config.Get().PortRange
	for i := 0; i < int(portRange); i++ {
		socket, err := net.Listen("tcp", fmt.Sprintf("%s:%d", addr, port+uint32(i)))
		if err == nil {
			logrus.Infoln("svr success listen in :", port+uint32(i))
			redisgw.RegisterSvr(port + uint32(i))
			//监听ctrl+c，做反注册处理

			p.ArpcSvr.Serve(socket)
			break
		}
	}
	logrus.Errorln("failed to listen port!")
	os.Exit(-5)
}

func (p *MyServer) Route(path string, handler func(*arpc.Context), args ...interface{}) {
	p.ArpcSvr.Handler.Handle(path, handler, args)
	logrus.Infoln("add path:", path)
}
